<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<%@ page import="com.bookmanager.model.Book" %>
<%@ page import="java.util.List" %>
<%@ page import="com.bookmanager.model.User" %>
<%
    // 检查管理员权限
    User user = (User) session.getAttribute("user");
    if (user == null || !"admin".equals(user.getRole())) {
        response.sendRedirect("../login.jsp");
        return;
    }

    List<Book> books = (List<Book>) request.getAttribute("books");
    String keyword = (String) request.getAttribute("keyword");
    if (keyword == null) keyword = "";
%>
<html>
<head>
    <title>图书管理 - 图书管理系统</title>
    <style>
        * {
            margin: 0;
            padding: 0;
            box-sizing: border-box;
        }

        body {
            font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
            background: #f5f7fa;
            color: #333;
        }

        .header {
            background: white;
            box-shadow: 0 2px 10px rgba(0,0,0,0.1);
            padding: 0 20px;
        }

        .nav-bar {
            display: flex;
            justify-content: space-between;
            align-items: center;
            max-width: 1200px;
            margin: 0 auto;
            height: 70px;
        }

        .logo {
            font-size: 1.5rem;
            font-weight: bold;
            color: #667eea;
        }

        .admin-info {
            display: flex;
            align-items: center;
            gap: 15px;
        }

        .admin-badge {
            background: #28a745;
            color: white;
            padding: 4px 8px;
            border-radius: 12px;
            font-size: 0.8rem;
            font-weight: 500;
        }

        .logout-btn {
            padding: 8px 16px;
            background: #dc3545;
            color: white;
            text-decoration: none;
            border-radius: 5px;
            font-size: 0.9rem;
        }

        .container {
            max-width: 1400px;
            margin: 30px auto;
            padding: 0 20px;
        }

        .page-header {
            display: flex;
            justify-content: space-between;
            align-items: center;
            margin-bottom: 30px;
            padding-bottom: 15px;
            border-bottom: 2px solid #eee;
        }

        .page-title {
            font-size: 1.8rem;
            color: #333;
        }

        .search-box {
            display: flex;
            gap: 15px;
            margin-bottom: 25px;
            background: white;
            padding: 20px;
            border-radius: 10px;
            box-shadow: 0 2px 10px rgba(0,0,0,0.1);
        }

        .search-input {
            flex: 1;
            padding: 12px 15px;
            border: 1px solid #ddd;
            border-radius: 6px;
            font-size: 14px;
        }

        .btn {
            padding: 12px 24px;
            border: none;
            border-radius: 6px;
            cursor: pointer;
            font-size: 14px;
            text-decoration: none;
            display: inline-flex;
            align-items: center;
            gap: 8px;
            transition: all 0.3s ease;
        }

        .btn-primary {
            background: #667eea;
            color: white;
        }

        .btn-success {
            background: #28a745;
            color: white;
        }

        .btn-secondary {
            background: #6c757d;
            color: white;
        }

        .btn-danger {
            background: #dc3545;
            color: white;
        }

        .btn-warning {
            background: #ffc107;
            color: #212529;
        }

        .btn:hover {
            opacity: 0.9;
            transform: translateY(-1px);
        }

        .book-table {
            width: 100%;
            background: white;
            border-radius: 10px;
            overflow: hidden;
            box-shadow: 0 5px 15px rgba(0,0,0,0.1);
        }

        .book-table th,
        .book-table td {
            padding: 15px;
            text-align: left;
            border-bottom: 1px solid #f0f0f0;
        }

        .book-table th {
            background: #f8f9fa;
            font-weight: 600;
            color: #555;
            border-bottom: 2px solid #e9ecef;
        }

        .book-table tr:hover {
            background: #f8f9fa;
        }

        .status-available {
            color: #28a745;
            font-weight: bold;
            background: #d4edda;
            padding: 4px 8px;
            border-radius: 12px;
            font-size: 0.8rem;
        }

        .status-borrowed {
            color: #dc3545;
            font-weight: bold;
            background: #f8d7da;
            padding: 4px 8px;
            border-radius: 12px;
            font-size: 0.8rem;
        }

        .action-buttons {
            display: flex;
            gap: 8px;
        }

        .btn-sm {
            padding: 6px 12px;
            font-size: 0.8rem;
        }

        .empty-state {
            text-align: center;
            padding: 60px 20px;
            color: #666;
            background: white;
            border-radius: 10px;
            box-shadow: 0 5px 15px rgba(0,0,0,0.1);
        }

        .empty-icon {
            font-size: 4rem;
            margin-bottom: 20px;
            opacity: 0.5;
        }

        .stats-cards {
            display: grid;
            grid-template-columns: repeat(auto-fit, minmax(200px, 1fr));
            gap: 20px;
            margin-bottom: 30px;
        }

        .stat-card {
            background: white;
            padding: 20px;
            border-radius: 10px;
            text-align: center;
            box-shadow: 0 5px 15px rgba(0,0,0,0.1);
        }

        .stat-icon {
            font-size: 2rem;
            margin-bottom: 10px;
        }

        .stat-number {
            font-size: 1.8rem;
            font-weight: bold;
            color: #667eea;
            margin-bottom: 5px;
        }

        .stat-label {
            color: #666;
            font-size: 0.9rem;
        }

        .alert {
            padding: 15px;
            margin-bottom: 20px;
            border-radius: 6px;
            font-size: 14px;
        }

        .alert-success {
            background: #d4edda;
            color: #155724;
            border: 1px solid #c3e6cb;
        }

        .alert-danger {
            background: #f8d7da;
            color: #721c24;
            border: 1px solid #f5c6cb;
        }

        .modal {
            display: none;
            position: fixed;
            z-index: 1000;
            left: 0;
            top: 0;
            width: 100%;
            height: 100%;
            background-color: rgba(0,0,0,0.5);
        }

        .modal-content {
            background-color: white;
            margin: 5% auto;
            padding: 30px;
            border-radius: 10px;
            width: 90%;
            max-width: 500px;
            box-shadow: 0 5px 25px rgba(0,0,0,0.2);
        }

        .close {
            float: right;
            font-size: 1.5rem;
            font-weight: bold;
            cursor: pointer;
            color: #666;
        }

        .close:hover {
            color: #333;
        }

        .form-group {
            margin-bottom: 20px;
        }

        .form-label {
            display: block;
            margin-bottom: 8px;
            font-weight: 600;
            color: #333;
        }

        .form-control {
            width: 100%;
            padding: 10px;
            border: 1px solid #ddd;
            border-radius: 5px;
            font-size: 14px;
            box-sizing: border-box;
        }

        .form-control:focus {
            border-color: #667eea;
            outline: none;
            box-shadow: 0 0 0 2px rgba(102, 126, 234, 0.2);
        }

        .modal-body::-webkit-scrollbar {
            width: 6px;
        }

        .modal-body::-webkit-scrollbar-track {
            background: #f1f1f1;
            border-radius: 3px;
        }

        .modal-body::-webkit-scrollbar-thumb {
            background: #c1c1c1;
            border-radius: 3px;
        }

        .modal-body::-webkit-scrollbar-thumb:hover {
            background: #a8a8a8;
        }

        /* 优化模态框样式 */
        .modal-content {
            background-color: white;
            margin: 2% auto;
            padding: 25px;
            border-radius: 12px;
            width: 90%;
            max-width: 600px;
            max-height: 90vh;
            box-shadow: 0 10px 30px rgba(0,0,0,0.3);
            display: flex;
            flex-direction: column;
        }

        .modal-body {
            flex: 1;
            overflow-y: auto;
        }

        /* 表单组优化 */
        .form-group {
            margin-bottom: 20px;
        }

        .form-label {
            display: block;
            margin-bottom: 8px;
            font-weight: 600;
            color: #333;
            font-size: 14px;
        }

        .form-control {
            width: 100%;
            padding: 12px;
            border: 1px solid #ddd;
            border-radius: 6px;
            font-size: 14px;
            box-sizing: border-box;
            transition: all 0.3s ease;
        }

        .form-control:focus {
            border-color: #667eea;
            outline: none;
            box-shadow: 0 0 0 3px rgba(102, 126, 234, 0.1);
        }

        /* 关闭按钮优化 */
        .close {
            float: right;
            font-size: 24px;
            font-weight: bold;
            cursor: pointer;
            color: #666;
            line-height: 1;
            padding: 5px;
        }

        .close:hover {
            color: #333;
            background: #f5f5f5;
            border-radius: 50%;
        }
    </style>
</head>
<body>
<!-- 顶部导航 -->
<div class="header">
    <div class="nav-bar">
        <div class="logo">📚 图书管理系统</div>
        <div class="admin-info">
            <span>欢迎，<strong><%= user.getUsername() %></strong></span>
            <span class="admin-badge">管理员</span>
            <a href="<%= request.getContextPath() %>/logout" class="logout-btn">退出登录</a>
        </div>
    </div>
</div>

<div class="container">
    <!-- 页面头部 -->
    <div class="page-header">
        <h1 class="page-title">📚 图书管理</h1>
        <div>
            <a href="../admin/dashboard.jsp" class="btn btn-secondary">返回控制台</a>
            <button class="btn btn-success" onclick="showAddBookModal()">
                <span>➕</span> 添加新书
            </button>
        </div>
    </div>

    <!-- 统计卡片 -->
    <div class="stats-cards">
        <div class="stat-card">
            <div class="stat-icon">📚</div>
            <div class="stat-number" id="totalBooks">0</div>
            <div class="stat-label">馆藏图书</div>
        </div>
        <div class="stat-card">
            <div class="stat-icon">📖</div>
            <div class="stat-number" id="availableBooks">0</div>
            <div class="stat-label">可借图书</div>
        </div>
        <div class="stat-card">
            <div class="stat-icon">⏰</div>
            <div class="stat-number" id="borrowedBooks">0</div>
            <div class="stat-label">已借出</div>
        </div>
        <div class="stat-card">
            <div class="stat-icon">📊</div>
            <div class="stat-number" id="totalCopies">0</div>
            <div class="stat-label">总册数</div>
        </div>
    </div>

    <!-- 搜索框 -->
    <div class="search-box">
        <form action="../books" method="get" style="display: flex; gap: 10px; width: 100%;">
            <input type="hidden" name="action" value="search">
            <input type="text" name="keyword" value="<%= keyword %>"
                   placeholder="输入书名、作者或ISBN进行搜索..." class="search-input">
            <button type="submit" class="btn btn-primary">🔍 搜索</button>
            <a href="../books" class="btn btn-secondary">显示全部</a>
        </form>
    </div>

    <!-- 消息提示 -->
    <%
        String message = request.getParameter("message");
        if (message != null) {
            String alertClass = "";
            String alertText = "";

            if ("add_success".equals(message)) {
                alertClass = "alert-success";
                alertText = "图书添加成功！";
            } else if ("add_failed".equals(message)) {
                alertClass = "alert-danger";
                alertText = "图书添加失败！";
            } else if ("update_success".equals(message)) {
                alertClass = "alert-success";
                alertText = "图书更新成功！";
            } else if ("update_failed".equals(message)) {
                alertClass = "alert-danger";
                alertText = "图书更新失败！";
            } else if ("delete_success".equals(message)) {
                alertClass = "alert-success";
                alertText = "图书删除成功！";
            } else if ("delete_failed".equals(message)) {
                alertClass = "alert-danger";
                alertText = "图书删除失败！";
            }

            if (!alertText.isEmpty()) {
    %>
    <div class="alert <%= alertClass %>">
        <%= alertText %>
    </div>
    <%
            }
        }
    %>

    <!-- 图书表格 -->
    <% if (books != null && !books.isEmpty()) { %>
    <div style="overflow-x: auto;">
        <table class="book-table">
            <thead>
            <tr>
                <th>ID</th>
                <th>ISBN</th>
                <th>书名</th>
                <th>作者</th>
                <th>出版社</th>
                <th>价格</th>
                <th>分类</th>
                <th>库存</th>
                <th>状态</th>
                <th>操作</th>
            </tr>
            </thead>
            <tbody>
            <% for (Book book : books) { %>
            <tr>
                <td><%= book.getBookId() %></td>
                <td><%= book.getIsbn() %></td>
                <td><strong><%= book.getTitle() %></strong></td>
                <td><%= book.getAuthor() %></td>
                <td><%= book.getPublisher() %></td>
                <td>¥<%= book.getPrice() != null ? book.getPrice() : "0.00" %></td>
                <td><%= book.getCategory() != null ? book.getCategory() : "未分类" %></td>
                <td><%= book.getAvailableCopies() %>/<%= book.getTotalCopies() %></td>
                <td>
                    <span class="status-<%= book.getStatus() %>">
                        <%= "available".equals(book.getStatus()) ? "可借" : "已借出" %>
                    </span>
                </td>
                <td>
                    <div class="action-buttons">
                        <button class="btn btn-primary btn-sm" onclick="editBook(<%= book.getBookId() %>)">编辑</button>
                        <button class="btn btn-warning btn-sm" onclick="showBookDetail(<%= book.getBookId() %>)">详情</button>
                        <button class="btn btn-danger btn-sm" onclick="deleteBook(<%= book.getBookId() %>, '<%= book.getTitle() %>')">删除</button>
                    </div>
                </td>
            </tr>
            <% } %>
            </tbody>
        </table>
    </div>
    <% } else { %>
    <div class="empty-state">
        <div class="empty-icon">📚</div>
        <h3>暂无图书数据</h3>
        <p>请添加图书或尝试其他搜索关键词</p>
        <button class="btn btn-success" onclick="showAddBookModal()" style="margin-top: 15px;">
            <span>➕</span> 添加第一本图书
        </button>
    </div>
    <% } %>
</div>

<!-- 添加图书模态框 -->
<div id="addBookModal" class="modal">
    <div class="modal-content">
        <span class="close" onclick="closeAddBookModal()">&times;</span>
        <h2 style="margin-bottom: 20px; padding-bottom: 15px; border-bottom: 1px solid #eee;">添加新图书</h2>

        <div class="modal-body" style="max-height: 70vh; overflow-y: auto; padding-right: 10px;">
            <form id="addBookForm" action="../books" method="post">
                <input type="hidden" name="action" value="add">

                <div class="form-group">
                    <label class="form-label">ISBN *</label>
                    <input type="text" name="isbn" class="form-control" required
                           placeholder="请输入ISBN号">
                </div>

                <div class="form-group">
                    <label class="form-label">书名 *</label>
                    <input type="text" name="title" class="form-control" required
                           placeholder="请输入书名">
                </div>

                <div class="form-group">
                    <label class="form-label">作者 *</label>
                    <input type="text" name="author" class="form-control" required
                           placeholder="请输入作者">
                </div>

                <div class="form-group">
                    <label class="form-label">出版社</label>
                    <input type="text" name="publisher" class="form-control"
                           placeholder="请输入出版社">
                </div>

                <div class="form-group">
                    <label class="form-label">出版日期</label>
                    <input type="date" name="publishDate" class="form-control">
                </div>

                <div class="form-group">
                    <label class="form-label">价格</label>
                    <input type="number" name="price" step="0.01" class="form-control"
                           placeholder="0.00">
                </div>

                <div class="form-group">
                    <label class="form-label">分类</label>
                    <input type="text" name="category" class="form-control"
                           placeholder="请输入分类">
                </div>

                <div class="form-group">
                    <label class="form-label">描述</label>
                    <textarea name="description" class="form-control" rows="3"
                              placeholder="请输入图书描述"></textarea>
                </div>

                <div class="form-group">
                    <label class="form-label">总数量 *</label>
                    <input type="number" name="totalCopies" class="form-control" value="1" min="1" required>
                </div>

                <div class="form-group">
                    <label class="form-label">可借数量 *</label>
                    <input type="number" name="availableCopies" class="form-control" value="1" min="0" required>
                </div>

                <div class="form-group">
                    <label class="form-label">位置</label>
                    <input type="text" name="location" class="form-control"
                           placeholder="请输入图书位置">
                </div>

                <div style="display: flex; gap: 10px; margin-top: 25px; padding-top: 15px; border-top: 1px solid #eee;">
                    <button type="submit" class="btn btn-success" style="flex: 1;">添加图书</button>
                    <button type="button" class="btn btn-secondary" onclick="closeAddBookModal()">取消</button>
                </div>
            </form>
        </div>
    </div>
</div>

<script>
    // 统计信息计算
    function calculateStats() {
        const books = <%= books != null ? books.size() : 0 %>;
        const available = <%= books != null ? books.stream().filter(b -> "available".equals(b.getStatus())).count() : 0 %>;
        const borrowed = <%= books != null ? books.stream().filter(b -> "borrowed".equals(b.getStatus())).count() : 0 %>;
        const totalCopies = <%= books != null ? books.stream().mapToInt(Book::getTotalCopies).sum() : 0 %>;

        document.getElementById('totalBooks').textContent = books;
        document.getElementById('availableBooks').textContent = available;
        document.getElementById('borrowedBooks').textContent = borrowed;
        document.getElementById('totalCopies').textContent = totalCopies;
    }

    function showAddBookModal() {
        document.getElementById('addBookModal').style.display = 'block';
        // 显示时滚动到顶部
        const modalBody = document.querySelector('.modal-body');
        if (modalBody) {
            modalBody.scrollTop = 0;
        }
    }

    function closeAddBookModal() {
        document.getElementById('addBookModal').style.display = 'none';
        // 重置表单
        document.getElementById('addBookForm').reset();
    }

    // 点击模态框外部关闭
    window.onclick = function(event) {
        const modal = document.getElementById('addBookModal');
        if (event.target === modal) {
            closeAddBookModal();
        }
    }

    // ESC键关闭模态框
    document.addEventListener('keydown', function(event) {
        if (event.key === 'Escape') {
            closeAddBookModal();
        }
    });

    // 表单提交验证
    document.getElementById('addBookForm').addEventListener('submit', function(e) {
        const isbn = this.querySelector('input[name="isbn"]').value;
        const title = this.querySelector('input[name="title"]').value;
        const author = this.querySelector('input[name="author"]').value;

        if (!isbn || !title || !author) {
            e.preventDefault();
            alert('请填写必填字段（ISBN、书名、作者）！');
            return;
        }

        // 可以添加更多验证逻辑
        const totalCopies = parseInt(this.querySelector('input[name="totalCopies"]').value);
        const availableCopies = parseInt(this.querySelector('input[name="availableCopies"]').value);

        if (availableCopies > totalCopies) {
            e.preventDefault();
            alert('可借数量不能大于总数量！');
            return;
        }
    });

    // 操作函数
    function editBook(bookId) {
        window.location.href = '../books?action=edit&bookId=' + bookId;
    }

    function showBookDetail(bookId) {
        window.location.href = '../book-detail?bookId=' + bookId;
    }

    function deleteBook(bookId, bookTitle) {
        if (confirm('确定要删除《' + bookTitle + '》吗？此操作不可恢复！')) {
            const form = document.createElement('form');
            form.method = 'POST';
            form.action = '../books';

            const actionInput = document.createElement('input');
            actionInput.type = 'hidden';
            actionInput.name = 'action';
            actionInput.value = 'delete';
            form.appendChild(actionInput);

            const bookIdInput = document.createElement('input');
            bookIdInput.type = 'hidden';
            bookIdInput.name = 'bookId';
            bookIdInput.value = bookId;
            form.appendChild(bookIdInput);

            document.body.appendChild(form);
            form.submit();
        }
    }

    // 页面加载完成后计算统计信息
    document.addEventListener('DOMContentLoaded', calculateStats);
</script>
</body>
</html>
